package com.sunyur.tailor.channel.service.outer.keep.service.impl;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.sunyur.tailor.channel.common.inner.base.MsgResultCode;
import com.sunyur.tailor.channel.common.inner.base.SunyurResult;
import com.sunyur.tailor.channel.common.inner.util.SunyurClientUtil;
import com.sunyur.tailor.channel.common.inner.util.SunyurResultUtil;
import com.sunyur.tailor.channel.common.middle.base.ChannelListResult;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.service.inner.findsource.model.FindSourceFixedInforHeadModel;
import com.sunyur.tailor.channel.service.inner.findsource.model.FindSourceFixedInforItemModel;
import com.sunyur.tailor.channel.service.inner.findsource.param.FindSourceInforParam;
import com.sunyur.tailor.channel.service.inner.findsource.service.SunyurFindSourceService;
import com.sunyur.tailor.channel.service.inner.purchase.model.PurchaserApplyHeadModel;

import com.sunyur.tailor.channel.service.inner.purchase.param.PurchaseApplyHeadByCodeParam;
import com.sunyur.tailor.channel.service.inner.purchase.service.SunyurPurchaseApplyService;
import com.sunyur.tailor.channel.service.outer.keep.param.FeishuForApprovalFormParam;
import com.sunyur.tailor.channel.service.outer.keep.param.SRMPurchaseFeishuForApprovalParam;
import com.sunyur.tailor.channel.service.outer.keep.service.KeepToFeishuService;
import com.sunyur.tailor.channel.service.outer.keep.service.WorkflowBusinessStrategyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * tenderOrder策略
 * SRM询价单定标结果发至飞书进行审批
 */
@Service("inquireOrder")
@Slf4j
public class InquireOrderStrategyImpl implements WorkflowBusinessStrategyService {

    @Autowired
    private SunyurFindSourceService service;

    @Autowired
    private SunyurClientUtil sunyurClient;
    @Value("${sunyur.api.findSourceFixedHead}")
    private String findSourceFixedHead;

    @Value("${sunyur.api.findSourceProjectList}")
    private String findSourceProjectList;

    @Value("${feishu.tenderOrder.approvalCode}")
    private String approvalCode;

    @Autowired
    private KeepToFeishuService keepToFeishuService;


    @Autowired
    private SunyurPurchaseApplyService sunyurPurchaseApplyService;

    @Override
    public ChannelResult start(MsgResultCode msgResultCode) {

        if(("commit").equals(msgResultCode.getAction()))
        {

            Integer type = 1;
            if(msgResultCode.getWorkflowBusiness().equals("tendOrder"))
            {
                log.info("tenderOrder start  msgResultCode:{}", JSONObject.toJSONString(msgResultCode));
                type=2;
            }else if(msgResultCode.getWorkflowBusiness().equals("inquireOrder"))
            {
                log.info("inquireOrder start  msgResultCode:{}", JSONObject.toJSONString(msgResultCode));
                type=1;
            }else if(msgResultCode.getWorkflowBusiness().equals("auctionOrder"))
            {
                log.info("auctionOrder start  msgResultCode:{}", JSONObject.toJSONString(msgResultCode));
                type=3;
            }



            SunyurResult sunyurResult =
                    sunyurClient.execPost(findSourceProjectList,
                            JSON.toJSONString(
                                    MapUtil.builder()
                                            .put("purCode", msgResultCode.getBusinessCode())
                                            .put("type", type)
                                            .build()), null);
            log.info("sunyurResult: {}", JSON.toJSONString(sunyurResult));
            // 主线报错
            if (!SunyurResultUtil.isSuccess(sunyurResult)) {
                log.error("findSourceProjectList loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(MapUtil.builder()
                        .put("purCode", msgResultCode.getBusinessCode())
                        .put("type", type)
                        .build()), JSON.toJSONString(sunyurResult));
                return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurResult.getErrorMessage());
            }
            List<Map<String, Object>> content = (List<Map<String, Object>>) sunyurResult.getContent();
            Long code = Long.valueOf(content.get(0).get("code").toString());
            log.info("code: {}", code);


            try {
                ChannelResult<FindSourceFixedInforHeadModel> findSourceFixedInforHeadModelChannelResult = service.searchFixedInforHead(new FindSourceInforParam(code));
                if (!ChannelResultUtil.isSuccess(findSourceFixedInforHeadModelChannelResult)) {
                    return findSourceFixedInforHeadModelChannelResult;
                }
                ChannelListResult<FindSourceFixedInforItemModel> findSourceFixedInforItemModelChannelListResult = service.searchFixedInforItem(new FindSourceInforParam(code));
                if (!ChannelResultUtil.isSuccess(findSourceFixedInforItemModelChannelListResult)) {
                    return findSourceFixedInforItemModelChannelListResult;
                }

                log.info("findSourceFixedInforHeadModelChannelResult: {}", JSON.toJSONString(findSourceFixedInforHeadModelChannelResult));
                log.info("findSourceFixedInforItemModelChannelListResult: {}", JSON.toJSONString(findSourceFixedInforItemModelChannelListResult));


                SRMPurchaseFeishuForApprovalParam srmPurchaseFeishuForApprovalParam = new SRMPurchaseFeishuForApprovalParam();
                //拼装请求参数
                srmPurchaseFeishuForApprovalParam.setApproval_code(approvalCode); //固定值
                srmPurchaseFeishuForApprovalParam.setUser_id(findSourceFixedInforHeadModelChannelResult.getContent().getAgentWorkNum()); //申请人id
                srmPurchaseFeishuForApprovalParam.setOpen_id(findSourceFixedInforHeadModelChannelResult.getContent().getAgentWorkNum()); //PR头/content/proposerCode
                ArrayList formList = new ArrayList();

                //widget1
                FeishuForApprovalFormParam widget1 = new FeishuForApprovalFormParam();
                widget1.setId("widget1");
                widget1.setType("input");
                widget1.setValue(findSourceFixedInforHeadModelChannelResult.getContent().getTittle());

                //widget2
                FeishuForApprovalFormParam widget2 = new FeishuForApprovalFormParam();
                widget2.setId("widget2");
                widget2.setType("input");
                widget2.setValue(findSourceFixedInforHeadModelChannelResult.getContent().getPurCode());

                //widget3
                FeishuForApprovalFormParam widget3 = new FeishuForApprovalFormParam();
                widget3.setId("widget3");
                widget3.setType("contact");

                if (CollectionUtils.isEmpty(findSourceFixedInforItemModelChannelListResult.getContent())) {
                    widget3.setValue(Arrays.asList(findSourceFixedInforHeadModelChannelResult.getContent().getAgentWorkNum()));
                } else {
                    List<FindSourceFixedInforItemModel> content1 = findSourceFixedInforItemModelChannelListResult.getContent();
                    List<String> upStreamCodeList = new ArrayList();
                    List<String> proposerCodeList = new ArrayList<>();

                    content1.forEach(item -> {
                                if (!StringUtils.isEmpty(item.getUpstreamCode())) {
                                    upStreamCodeList.add(item.getUpstreamCode());
                                }
                            }
                    );
                    if (upStreamCodeList.size() == 0) {
                        widget3.setValue(Arrays.asList(findSourceFixedInforHeadModelChannelResult.getContent().getAgentWorkNum()));
                    } else {
                        for (String s : upStreamCodeList) {
                            PurchaseApplyHeadByCodeParam purchaseApplyHeadByCodeParam = new PurchaseApplyHeadByCodeParam();
                            purchaseApplyHeadByCodeParam.setApplyCode(s);
                            ChannelResult<PurchaserApplyHeadModel> purchaserApplyHeadByCode = sunyurPurchaseApplyService.getPurchaserApplyHeadByCode(purchaseApplyHeadByCodeParam);
                            proposerCodeList.add(purchaserApplyHeadByCode.getContent().getProposerCode());
                        }
                        List<String> disProposerCodeList = proposerCodeList.stream().distinct().collect(Collectors.toList());

                        widget3.setValue(disProposerCodeList);
                    }
                }

                //widget4
                FeishuForApprovalFormParam widget4 = new FeishuForApprovalFormParam();
                widget4.setId("widget4");
                widget4.setType("input");
                widget4.setValue(findSourceFixedInforHeadModelChannelResult.getContent().getPurchaseOrgName());

                //widget5
                FeishuForApprovalFormParam widget5 = new FeishuForApprovalFormParam();
                widget5.setId("widget5");
                widget5.setType("contact");
                widget5.setValue(Arrays.asList(findSourceFixedInforHeadModelChannelResult.getContent().getAgentWorkNum()));

                //widget6
                FeishuForApprovalFormParam widget6 = new FeishuForApprovalFormParam();
                widget6.setId("widget6");
                widget6.setType("fieldList");
                widget6.setValue(getValue6(findSourceFixedInforItemModelChannelListResult));

                //widget7
                FeishuForApprovalFormParam widget7 = new FeishuForApprovalFormParam();
                widget7.setId("widget7");
                widget7.setType("fieldList");
                widget7.setValue(getValue7(findSourceFixedInforHeadModelChannelResult));

                formList.add(widget1);
                formList.add(widget2);
                formList.add(widget3);
                formList.add(widget4);

                formList.add(widget5);
                formList.add(widget6);
                formList.add(widget7);

                srmPurchaseFeishuForApprovalParam.setForm(JSONObject.toJSONString(formList));

                log.info("srmPurchaseFeishuForApprovalParam: {}", JSON.toJSONString(srmPurchaseFeishuForApprovalParam));

                //创建审批实例
                ChannelResult<Boolean> booleanChannelResult = keepToFeishuService.sRMPurchaseFeishuForApproval(msgResultCode,srmPurchaseFeishuForApprovalParam);

                return booleanChannelResult;



            } catch (Exception e) {
                return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), e.getMessage());
            }
        }

        return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "参数错误");


    }

    public List<List<FeishuForApprovalFormParam>> getValue7(ChannelResult<FindSourceFixedInforHeadModel> findSourceFixedInforHeadModelChannelResult)
    {
        List first =new ArrayList();
        List second =new ArrayList();

        second.add(new FeishuForApprovalFormParam("widget7_1", "input", findSourceFixedInforHeadModelChannelResult.getContent().getAwardSchemeInfo().get("awardSchemeName")));
        second.add(new FeishuForApprovalFormParam("widget7_2", "textarea", findSourceFixedInforHeadModelChannelResult.getContent().getRemark()
                .replaceAll("<p>", "").replaceAll("</p>", "\n")
                .replaceAll("<br>", "").replaceAll("</br>", "\n")));

        first.add(second);


        return first;
    }




    public List<List<FeishuForApprovalFormParam>> getValue6(ChannelListResult<FindSourceFixedInforItemModel> findSourceFixedInforItemModelChannelListResult)
    {
        List<FindSourceFixedInforItemModel> content = findSourceFixedInforItemModelChannelListResult.getContent();
        List first =new ArrayList();
        for (FindSourceFixedInforItemModel findSourceFixedInforItemModel : content) {
            FeishuForApprovalFormParam widget6_1 = new FeishuForApprovalFormParam();
            widget6_1.setId("widget6_1");
            widget6_1.setType("input");
            widget6_1.setValue(findSourceFixedInforItemModel.getSupplierName());

            FeishuForApprovalFormParam widget6_2 = new FeishuForApprovalFormParam();
            widget6_2.setId("widget6_2");
            widget6_2.setType("input");
            widget6_2.setValue(findSourceFixedInforItemModel.getMaterielName());

            FeishuForApprovalFormParam widget6_3 = new FeishuForApprovalFormParam();
            widget6_3.setId("widget6_3");
            widget6_3.setType("input");
            widget6_3.setValue(findSourceFixedInforItemModel.getAmount().setScale(2, RoundingMode.HALF_UP).toString());

            List two =new ArrayList();
            two.add(widget6_1);
            two.add(widget6_2);
            two.add(widget6_3);
            first.add(two);
        }

        return first;
    }
}
